using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Security;
using Animoso.Domain;
using Animoso.Domain.Data;
using StructureMap;

namespace Animoso.Web.Controllers
{
    public abstract class ApplicationController : Controller
    {
        protected ApplicationController()
        {
            FillSections();
            FillUpcomingEvents();
            FillLinkItems();
            FillSponsors();
            FillIntroduction();
        }

        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            string name = HttpContext.User.Identity.Name;
            IUserRepository userRepository = ObjectFactory.GetInstance<IUserRepository>();

            try { userRepository.GetByUsername(name); }
            catch (NotFoundException)
            {
                FormsAuthentication.SignOut();
            }
            base.OnAuthorization(filterContext);
        }
        
        private void FillLinkItems()
        {
            IRepository<LinkItem> linkItemRepository = ObjectFactory.GetInstance<IRepository<LinkItem>>();
            ViewData["LinkItems"] = linkItemRepository.GetAll() ?? new List<LinkItem>();
        }

        private void FillSections()
        {
            ISectionRepository sectionRepository = ObjectFactory.GetInstance<ISectionRepository>();
            ViewData["SectionsLeft"] = sectionRepository.GetSectionsByPosition(Position.Left) ?? new List<Section>();
            ViewData["SectionsTop"] = sectionRepository.GetSectionsByPosition(Position.Top) ?? new List<Section>();
        }

        private void FillUpcomingEvents()
        {
            IEventRepository eventRepository = ObjectFactory.GetInstance<IEventRepository>();
            ViewData["EventItems"] = eventRepository.GetUpcomingEvents(DateTime.Now,10) ?? new List<Event>();
        }

        private void FillSponsors()
        {
            ISponsorRepository sponsorRepository = ObjectFactory.GetInstance<ISponsorRepository>();
            ViewData["footerSponsor"] = sponsorRepository.GetSponsorByImageLocation(ImageLocation.Footer);
            ViewData["marqueeSponsors"] = sponsorRepository.GetSponsorsByImageLocation(ImageLocation.Carousel);

            ViewData["Sponsoren"] = sponsorRepository.GetAll();
        }

        private void FillIntroduction()
        {
            IIntroductionRepository introductionRepository = ObjectFactory.GetInstance<IIntroductionRepository>();
            ViewData["hasIntroduction"] = introductionRepository.HasIntroductionByYear(DateTime.Now.Year);
        }
    }
}
